export function getMonth(l: number) {
  const arr = [];
  for (let i = 0; i < l; i++) {
    arr.push({ value: i + 1, label: `${i + 1}月` });
  }
  return arr;
}
export function getYear(l: number) {
  const arr = [];
  const year = new Date().getFullYear();
  for (let i = 0; i < l; i++) {
    arr.push({ value: year - i, label: `${year - i}` });
  }
  return arr;
}

export function getDisplayName(type: any) {
  const obj = {
    work: '工作经历',
    project: '项目经历',
    education: '教育经历',
    certificate: '荣誉证书',
    skills: '技能特长',
    school: '校园经历',
    internship: '实习经历',
    selfevaluation: '自我评价',
    custom: '自定义',
    hobby: '兴趣爱好',
  };
  return obj[type];
}

export function getInitContent(type: any) {
  const content: any = {
    work: {
      displayName: '工作经历',
      iconKey: 'briefcase',
      sectionType: 'work',
      entries: [],
    },
    project: {
      displayName: '项目经历',
      iconKey: 'folderOpen',
      sectionType: 'project',
      entries: [],
    },
    education: {
      displayName: '教育经历',
      iconKey: 'cap',
      sectionType: 'education',
      entries: [],
    },
    certificate: {
      displayName: '荣誉证书',
      iconKey: 'award',
      sectionType: 'certificate',
      entries: [],
    },
    skills: {
      displayName: '技能特长',
      iconKey: 'guitar',
      sectionType: 'skills',
      entries: [],
    },
    hobby: {
      displayName: '兴趣爱好',
      iconKey: 'guitar',
      sectionType: 'hobby',
      entries: [],
    },
    school: {
      displayName: '校园经历',
      iconKey: 'landmark',
      sectionType: 'school',
      entries: [],
    },
    internship: {
      displayName: '实习经历',
      iconKey: 'penClip',
      sectionType: 'internship',
      entries: [],
    },
    selfevaluation: {
      displayName: '自我评价',
      iconKey: 'chartUser',
      sectionType: 'selfevaluation',
      entries: [],
    },
    custom: {
      displayName: '自定义',
      iconKey: 'lightbulb',
      sectionType: 'custom',
      entries: [],
    },
  };
  return content[type];
}

export function isNil(v) {
  return v == null || v === '';
}

export function isSameValue(v1, v2) {
  if (isNil(v1) && isNil(v2)) return true;
  if (v1 === v2) return true;
  return false;
}

export const isClient = () => process.title === 'browser';

export const isProd = process.env.BUILD_ENV === 'prod';
export const isStg = process.env.BUILD_ENV === 'stg';

export function isMobile(userAgent) {
  return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(
    userAgent,
  );
}

export function isAndroid() {
  const u = navigator.userAgent;
  return (
    u.toLocaleLowerCase().includes('android') ||
    u.toLocaleLowerCase().includes('adr')
  ); // 判断是否是 android终端
}

export function reorder(list: any[], startIndex: number, endIndex: number) {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
}

export function move(
  source: any[],
  destination: any[],
  droppableSource: any,
  droppableDestination: any,
) {
  const sourceClone = Array.from(source);
  const destClone = Array.from(destination);
  const [removed] = sourceClone.splice(droppableSource.index, 1);

  destClone.splice(droppableDestination.index, 0, removed);

  const result: any = {};
  result[droppableSource.droppableId] = sourceClone;
  result[droppableDestination.droppableId] = destClone;

  return result;
}

export function debounce(fn, wait) {
  let timer = null;
  return function (...res) {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      return fn.apply(this, res);
    }, wait);
  };
}
export function multiplyFontSize(htmlString, a) {
  // 定义一个正则表达式，用于匹配带有 font-size 属性的样式，支持 px 和 pt 单位
  const regex = /font-size:\s*([\d.]+)(px|pt);/g;

  // 使用 replace 方法替换匹配到的样式属性值
  const updatedHtml = htmlString.replace(regex, (match, fontSize, unit) => {
    // 将匹配到的 font-size 属性值转换为数值，并乘以变量 a
    const newSize = Number.parseFloat(fontSize) * a;
    // 根据原始单位重新构建属性值
    return `font-size: ${newSize}${unit};`;
  });

  return updatedHtml;
}
export function isWeixin(userAgent?) {
  const ua = (userAgent || navigator.userAgent).toLowerCase();
  return ua.includes('micromessenger');
}
export function forbidChangeFontsize() {
  if (isWeixin()) {
    if (
      typeof WeixinJSBridge == 'object' &&
      typeof WeixinJSBridge.invoke == 'function'
    ) {
      handleFontSize();
    } else {
      if (document.addEventListener) {
        document.addEventListener('WeixinJSBridgeReady', handleFontSize, false);
      }
    }
  }

  function handleFontSize() {
    // 设置网页字体为默认大小
    WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 });
    // 重写设置网页字体大小的事件
    WeixinJSBridge.on('menu:setfont', () => {
      WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 });
    });
  }
}

export function blobToFile(theBlob: Blob, fileName: string, type: string) {
  return new File([theBlob], fileName, { type });
}

function supportsWebp({ createImageBitmap, Image }): Promise<boolean> {
  if (!createImageBitmap || !Image) return Promise.resolve(false);

  return new Promise((resolve) => {
    const image = new Image();
    image.onload = () => {
      createImageBitmap(image)
        .then(() => {
          resolve(true);
        })
        .catch(() => {
          resolve(false);
        });
    };
    image.onerror = () => {
      resolve(false);
    };
    image.src =
      '';
  });
}

export function webpIsSupported() {
  return supportsWebp(window);
}
export const options = [
  {
    label: '全部',
    value: 0,
    type: 'list',
  },
  {
    label: '简洁',
    value: 2,
    type: 'jianjie',
  },
  {
    label: '双栏',
    value: 4,
    type: 'shuanglan',
  },
  {
    label: '表格',
    value: 8,
    type: 'table',
  },
  {
    label: '应届生',
    value: 16,
    type: 'yingjiesheng',
  },
  {
    label: '精美',
    value: 32,
    type: 'jingmei',
  },
  {
    label: '热门',
    value: 64,
    type: 'remen',
  },
];

export function getStyle() {
  const style: any = document.querySelector('style[data-styled]');
  const styledComponentsStyles = Array.from(style?.sheet?.rules)
    ?.map((r: any) => r.cssText)
    ?.join('\n\n');
  return `
  <style>
   body{font-size:16px;color:#333;word-break:break-word;font-family:"Helvetica Neue",Arial,"PingFang SC","Microsoft YaHei",SimSun,sans-serif;text-size-adjust:none!important;text-size-adjust:100%!important;-webkit-text-size-adjust:none!important;-webkit-text-size-adjust:100%!important}*{box-sizing:border-box}html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0}table{width:100%}article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block}body{line-height:1;list-style:inside}ul{list-style:none}a{text-decoration:none}blockquote,q{quotes:none}blockquote:before,blockquote:after,q:before,q:after{content:"";content:none}table{border-collapse:collapse;border-spacing:0}button{font-feature-settings:inherit;color:inherit;font-family:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;line-height:inherit;margin:0;padding:0;text-transform:none;background-color:transparent;background-image:none;appearance:none;border:none;outline:none}.leftSection>div:last-child{padding-bottom:0!important}.rightSection>div:last-child{padding-bottom:0!important}.personalInfo+div .leftSection{padding-top:0!important}
  </style>
  <style>
  ${styledComponentsStyles?.replace(/\/\*[\s\S]*?\*\//g, '')}
  </style>
  `;
}

export function createDomContainer(htmlString) {
  if (typeof document !== 'undefined') {
    // 浏览器环境
    const container = document.createElement('div');
    container.innerHTML = htmlString;
    return container;
  }
}

export function addValueToOlLi(htmlString) {
  // 创建 DOM 容器
  const container = createDomContainer(htmlString);

  // 查找所有 <ol> 标签
  const olElements = container.querySelectorAll('ol');

  // 遍历每个 <ol> 标签
  olElements.forEach((ol) => {
    // 获取所有子 <li> 元素
    const liElements = ol.querySelectorAll('li');

    // 为每个 <li> 添加 value 属性
    liElements.forEach((li, index) => {
      li.setAttribute('value', `${index + 1}`);
    });
  });

  // 返回修改后的 HTML 字符串
  return container.innerHTML;
}
